package link_list

// https://leetcode.cn/problems/add-two-numbers leetcode-2
func addTwoNumbers0(l1 *ListNode, l2 *ListNode) *ListNode {
	var node *ListNode
	var result *ListNode
	for l1 != nil || l2 != nil {
		var v1, v2 int
		if l1 != nil {
			v1 = l1.Val
			l1 = l1.Next
		}

		if l2 != nil {
			v2 = l2.Val
			l2 = l2.Next
		}
		// 第一次考虑进位
		nextNode := returnNode(v1 + v2)

		if node == nil {
			node = nextNode
			result = node
		} else {
			if node.Next != nil {
				nextNode.Val += node.Next.Val
				// 第二次考虑进位
				nextNode = addNode(nextNode)
			}

			node.Next = nextNode
			node = node.Next
		}
	}
	return result
}

func addNode(node *ListNode) *ListNode {
	if node.Val < 10 {
		return node
	}
	node.Val -= 10
	if node.Next != nil {
		node.Next.Val += 1
	} else {
		node.Next = &ListNode{
			Val:  1,
			Next: nil,
		}
	}
	return node
}

func returnNode(r int) *ListNode {
	var nextNode *ListNode
	if r > 9 {
		first := r % 10
		second := r / 10
		nextNode = &ListNode{
			Val: first,
			Next: &ListNode{
				Val:  second,
				Next: nil,
			},
		}
	} else {
		nextNode = &ListNode{
			Val:  r,
			Next: nil,
		}
	}
	return nextNode
}

func addTwoNumbers1(l1 *ListNode, l2 *ListNode) *ListNode {
	var result, tmp *ListNode
	sum := 0
	for l1 != nil || l2 != nil || sum != 0 {
		if l1 != nil {
			sum += l1.Val
			l1 = l1.Next
		}

		if l2 != nil {
			sum += l2.Val
			l2 = l2.Next
		}
		nextNode := &ListNode{Val: sum % 10}
		if result == nil {
			result = nextNode
			tmp = result
		} else {
			tmp.Next = nextNode
			tmp = tmp.Next
		}
		sum = sum / 10
	}
	return result
}
